import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Space, TimePicker, InputNumber } from 'antd';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import moment from 'moment';

const TimeBasedPricingEditor = ({ value, onChange }) => {
    const [internalValue, setInternalValue] = useState([]);

    useEffect(() => {
        if (value) {
            try {
                const parsedValue = JSON.parse(value);
                if (Array.isArray(parsedValue)) {
                    setInternalValue(parsedValue.map(item => ({
                        ...item,
                        time_range: [moment(item.start_time, 'HH:mm'), moment(item.end_time, 'HH:mm')]
                    })));
                }
            } catch (e) {
                // ignore
            }
        }
    }, [value]);

    const triggerChange = (changedValue) => {
        if (onChange) {
            const formattedValue = changedValue.map(item => ({
                start_time: item.time_range ? item.time_range[0].format('HH:mm') : '',
                end_time: item.time_range ? item.time_range[1].format('HH:mm') : '',
                price: item.price
            }));
            onChange(JSON.stringify(formattedValue));
        }
    };

    const handleAdd = () => {
        const newValue = [...internalValue, { time_range: [moment('00:00', 'HH:mm'), moment('23:59', 'HH:mm')], price: 0 }];
        setInternalValue(newValue);
        triggerChange(newValue);
    };

    const handleRemove = (index) => {
        const newValue = internalValue.filter((_, i) => i !== index);
        setInternalValue(newValue);
        triggerChange(newValue);
    };

    const handleChange = (index, field, fieldValue) => {
        const newValue = [...internalValue];
        newValue[index][field] = fieldValue;
        setInternalValue(newValue);
        triggerChange(newValue);
    };

    return (
        <div>
            {internalValue.map((item, index) => (
                <Space key={index} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                    <TimePicker.RangePicker
                        value={item.time_range}
                        format="HH:mm"
                        onChange={(time) => handleChange(index, 'time_range', time)}
                    />
                    <InputNumber
                        min={0}
                        precision={2}
                        value={item.price}
                        onChange={(price) => handleChange(index, 'price', price)}
                        addonBefore="¥"
                    />
                    <MinusCircleOutlined onClick={() => handleRemove(index)} />
                </Space>
            ))}
            <Button type="dashed" onClick={handleAdd} block icon={<PlusOutlined />}>
                添加时段
            </Button>
        </div>
    );
};

export default TimeBasedPricingEditor;